package com.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.pojo.Dept;
import com.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DeptController {

    @Autowired
    DeptService deptService;
    @Autowired
    private DiscoveryClient client;


    /**
     * 查询部门信息
     * 如果查询出现异常,则走hystrixGet这段备选代码
     * @param
     * @return
     */
    @HystrixCommand(fallbackMethod = "hystrixGet")
    @RequestMapping("/dept")//根据id查询
    public List<Dept> get(){
        List<Dept> list= deptService.getDepartments();
        if (list.size()==0){
            throw new RuntimeException("不存在该用户，或信息无法找到~");
        }
        return list;
    }


    @DeleteMapping("/dept/{id}")
    public void deleteDept(@PathVariable int id){
       deptService.deleteDept(id);
    }

    @PostMapping("/dept")
    public void addDept(Dept dept){
        deptService.addDept(dept);
    }

    @GetMapping("/dept/discovery")
    public Object discovery() {
        // 获取微服务列表的清单
        List<String> services = client.getServices();
        System.out.println("discovery=>services:" + services);
        // 得到一个具体的微服务信息,通过具体的微服务id，applicaioinName；
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-7001");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost() + "\t" + // 主机名称
                            instance.getPort() + "\t" + // 端口号
                            instance.getUri() + "\t" + // uri
                            instance.getServiceId() // 服务id
            );
        }
        return this.client;
    }

    public List<Dept> hystrixGet(){
          List<Dept> list= new ArrayList<>();
           Dept dept= new Dept();
           dept.setId(0);
           dept.setName("无信息！！");
           list.add(dept);
           return list;
    }
}
